package com.teradata.dashboard.ui.fragment;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.animation.RotateAnimation;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.teradata.dashboard.R;
import com.teradata.dashboard.adapter.KpiCategoryGroupAdapter;
import com.teradata.dashboard.service.KpiDataService;
import com.teradata.dashboard.ui.activity.KpiDetailActivity;
import com.teradata.dashboard.ui.activity.MainActivity;
import com.teradata.dashboard.ui.activity.MainActivity.MyTouchListener;
import com.teradata.dashboard.utils.HttpUtil;

public class KpiListFragment extends Fragment {

	private GestureDetector ges;
	String categoryId = "";
	private JSONArray kpiGroups;
	static final int NOTIFYCATION_ID=0x123;
	NotificationManager notifycationManager;
	private OnRefreshListener refreshListener;

	private boolean isRefreshable;
	private int startY;
	private int firstItemIndex;

	private int state;
	// 实际的padding的距离与界面上偏移距离的比例
	private final static int RATIO = 3;

	private boolean isBack;
	private boolean isRecored;

	private int headContentWidth;
	private int headContentHeight;
	private final static int RELEASE_To_REFRESH = 0;
	private final static int PULL_To_REFRESH = 1;
	private final static int REFRESHING = 2;
	private final static int DONE = 3;
	private final static int LOADING = 4;
	private LinearLayout headView;

	private TextView tipsTextview;
	private TextView lastUpdatedTextView;
	private ImageView arrowImageView;
	private ProgressBar progressBar;

	private RotateAnimation animation;
	private RotateAnimation reverseAnimation;
	
	  
    private KpiDataService.KpiDataBinder kpiDataBinder ;
	


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View messageLayout = inflater.inflate(R.layout.kpiview, container,
				false);
		System.out.println("KpiListFragment input");
		Bundle args=getArguments();
		categoryId=args.getString(KpiFragment.SELECTED_CATEGORY_ID);
		ges = new GestureDetector(getActivity(), onGestureListener); 
		//在该Fragment的构造函数中注册mTouchListener的回调
		((MainActivity)this.getActivity()).registerMyTouchListener(mTouchListener);
		return messageLayout;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		notifycationManager=(NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
		
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState){
		super.onActivityCreated(savedInstanceState);
		
		Intent intent=new Intent(this.getActivity(),KpiDataService.class);
    	/*ServiceConnection conn=new ServiceConnection(){		  
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				kpiDataBinder=(KpiDataService.KpiDataBinder) service;
				System.out.println("onServiceConnected:"+name+" ;time:"+kpiDataBinder.getLastUpdateTime());
				
			}
			@Override
			public void onServiceDisconnected(ComponentName name) {
				 System.out.println("onServiceDisconnected:"+name);
				
			}  
	   };
	   this.getActivity().bindService(intent,conn,Context.BIND_AUTO_CREATE);
	   this.getActivity().startService(intent);*/
	   
	   try {
			
			System.out.println("--------请求kpi前----------");
			kpiGroups = queryKpiCategoryGroup();
			System.out.println("--------请求kpi后----------");
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		initView();
		
	}
	
	@Override
	public void onResume() {
		super.onResume();
		initView();
	}
	
	private void initView() {
		WebView wv = (WebView) getView().findViewById(R.id.firstKpisWB);  
		wv.setBackgroundColor(Color.argb(0xff, 0xff, 0xff, 0xff));
        wv.getSettings().setJavaScriptEnabled(true);  
        wv.getSettings().setUseWideViewPort(true);
        wv.getSettings().setSupportZoom(true); 
        wv.getSettings().setBuiltInZoomControls(true);
        wv.getSettings().setLoadWithOverviewMode(true);  
        wv.requestFocus();  
        wv.loadUrl("file:///android_asset/html/column.html");
		
     
		KpiCategoryGroupAdapter kpiCategoryGroupAdapter=new KpiCategoryGroupAdapter(getActivity(),kpiGroups);
		ListView myListView=(ListView)getView().findViewById(R.id.kpi_listview);		
		myListView.setAdapter(kpiCategoryGroupAdapter);
		
		
		myListView.setOnItemClickListener(new ListView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long id) {
				 // TODO Auto-generated method stub
                Intent intent = new Intent();
                //Intent传递参数
                
                //kpiGroups.getJSONArray(index);
                
                try {
                JSONObject json = kpiGroups.getJSONObject(position);

                
                intent.putExtra("kpiId", json.getString("REF_KPI_ID"));
                intent.putExtra("kpiName", json.getString("KPI_GROUP_NAME"));
                //intent.putExtra("categoryNmae", json.getString("kpiGroupId"));
                intent.putExtra("KPI_CATEGORY_ID",categoryId);
                intent.putExtra("KPI_GROUP_ID", json.getString("KPI_GROUP_ID"));
                
                intent.putExtra("LAST_FREQ_VALUE", json.getString("LAST_FREQ_VALUE"));
                intent.putExtra("LAST_YEAR_VALUE", json.getString("LAST_YEAR_VALUE"));
                intent.putExtra("LAST_YEAR_END_VALUE", json.getString("LAST_YEAR_END_VALUE"));
                
                System.out.print("=--======="+json.toString());
                intent.putExtra("json", json.toString());
                
                intent.setClass(getActivity(), KpiDetailActivity.class);                
                getActivity().startActivity(intent);
                
				} catch (JSONException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
		});
		myListView.setOnItemLongClickListener(new ListView.OnItemLongClickListener() {

			@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
			@Override
			public boolean onItemLongClick(AdapterView<?> activity, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Toast.makeText(getActivity(), position+"", Toast.LENGTH_SHORT).show();
				Notification notify=new Notification.Builder(getActivity())
									.setAutoCancel(true)
									.setTicker("有新消息")
									.setSmallIcon(R.drawable.arrow1)
									.setContentTitle("一条新消息")
									.setContentText("你点击了第"+position+"个指标")
									.setDefaults(Notification.DEFAULT_SOUND).build();
				notifycationManager.notify(NOTIFYCATION_ID, notify);
				return true;
			}

			
		});
		myListView.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				Toast.makeText(getActivity(), arg2+"", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				//TODO Auto-generated method stub
			}			
		});
		
	}

	// 获取kpiCategory列表
		private JSONArray queryKpiCategoryGroup() throws Exception {
			// 使用Map封装请求参数
			Map<String, String> map = new HashMap<String, String>();

			// 定义发送请求的URL
			String url = HttpUtil.BASE_URL + "dashboard/listKpiValue.action?kpiCategoryId=CDS100000000&FREQ_ID=00&DIM_VALUE_ID1=00000000&DATA_DATE=20130131";
			
			JSONObject rtnObject=new JSONObject(HttpUtil.postRequest(url, map));
			if(rtnObject.getJSONArray("data")!=null){
				kpiGroups=rtnObject.getJSONArray("data");
			}
			
			return kpiGroups;
		}

		private GestureDetector.OnGestureListener onGestureListener = 
				new GestureDetector.SimpleOnGestureListener(){
					@Override
					public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
							float velocityY) {
						float x = e2.getX() - e1.getX();
						if(x<0)
						{
							
						}
						else if(x>0)
						{
							
						}
						return true;
					}
					
				};
				
		public boolean onTouchEvent(MotionEvent event)
			{
					return ges.onTouchEvent(event);
			}
	/**
	 * Fragment中，注册 接收MainActivity的Touch回调的对象
	 * 重写其中的onTouchEvent函数，并进行该Fragment的逻辑处理
	 */
	private MainActivity.MyTouchListener mTouchListener = new MyTouchListener() {
		@Override
		public void onTouchEvent(MotionEvent event) {
			if(event.getAction() == MotionEvent.ACTION_UP){
                //逻辑处理
         }
		}
	};

	// 当状态改变时候，调用该方法，以更新界面
	private void changeHeaderViewByState() {
		switch (state) {
		case RELEASE_To_REFRESH:
			arrowImageView.setVisibility(View.VISIBLE);
			progressBar.setVisibility(View.GONE);
			tipsTextview.setVisibility(View.VISIBLE);
			lastUpdatedTextView.setVisibility(View.VISIBLE);

			arrowImageView.clearAnimation();
			arrowImageView.startAnimation(animation);

			tipsTextview.setText("松开进行刷新");

			// Log.v(TAG, "当前状态，松开刷新");
			break;
		case PULL_To_REFRESH:
			progressBar.setVisibility(View.GONE);
			tipsTextview.setVisibility(View.VISIBLE);
			lastUpdatedTextView.setVisibility(View.VISIBLE);
			arrowImageView.clearAnimation();
			arrowImageView.setVisibility(View.VISIBLE);
			// 是由RELEASE_To_REFRESH状态转变来的
			if (isBack) {
				isBack = false;
				arrowImageView.clearAnimation();
				arrowImageView.startAnimation(reverseAnimation);

				tipsTextview.setText("向下拖动进行刷新");
			} else {
				tipsTextview.setText("向下拖动进行刷新");
			}
			// Log.v(TAG, "当前状态，下拉刷新");
			break;

		case REFRESHING:

			headView.setPadding(0, 0, 0, 0);

			progressBar.setVisibility(View.VISIBLE);
			arrowImageView.clearAnimation();
			arrowImageView.setVisibility(View.GONE);
			tipsTextview.setText("正在刷新...");
			lastUpdatedTextView.setVisibility(View.VISIBLE);

			// Log.v(TAG, "当前状态,正在刷新...");
			break;
		case DONE:
			headView.setPadding(0, -1 * headContentHeight, 0, 0);

			progressBar.setVisibility(View.GONE);
			arrowImageView.clearAnimation();
			arrowImageView.setImageResource(R.drawable.ic_pulltorefresh_arrow);
			tipsTextview.setText("松开进行刷新");
			lastUpdatedTextView.setVisibility(View.VISIBLE);

			// Log.v(TAG, "当前状态，done");
			break;
		}
	}

	public void setOnRefreshListener(OnRefreshListener refreshListener) {
		this.refreshListener = refreshListener;
		isRefreshable = true;
	}

	public interface OnRefreshListener {
		public void onRefresh();
	}

	public void onRefreshComplete() {
		state = DONE;
		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日  HH:mm");
		String date = format.format(new Date());
		lastUpdatedTextView.setText("上次刷新 ：" + date);
		changeHeaderViewByState();
	}

	private void onRefresh() {
		if (null != refreshListener) {
			refreshListener.onRefresh();
		}
	}

	// 此方法直接照搬自网络上的一个下拉刷新的demo，此处是“估计”headView的width以及height
	private void measureView(View child) {
		ViewGroup.LayoutParams p = child.getLayoutParams();
		if (p == null) {
			p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
		}

		int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
		int lpHeight = p.height;
		int childHeightSpec;
		if (lpHeight > 0) {
			childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
					MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = MeasureSpec.makeMeasureSpec(0,
					MeasureSpec.UNSPECIFIED);
		}
		child.measure(childWidthSpec, childHeightSpec);
	}

	public void setAdapter(BaseAdapter adapter) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日  HH:mm");
		String date = format.format(new Date());
		lastUpdatedTextView.setText("上次刷新:" + date);
		//super.setAdapter(adapter);
	}
	
	
	
	
}
